package com.zxk.blog.service.impl;

import com.zxk.blog.service.EsSearchDataService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class EsSearchDataServiceImpl implements EsSearchDataService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public List<Map<String, Object>> searchData(String Field,String keyword, Integer pageSize, Integer pageNo, String index) {
        List<Map<String,Object>> list = new ArrayList<>();
        try {
            SearchRequest request = new SearchRequest(index);
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery(Field, keyword);
            FieldSortBuilder sortBuilder = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);
            sourceBuilder.from(pageNo);
            sourceBuilder.size(pageSize);

            //高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("title");
            highlightBuilder.preTags("<span style='color:blue'>");
            highlightBuilder.postTags("</span>");
            sourceBuilder.highlighter(highlightBuilder);

            sourceBuilder.query(queryBuilder);
            sourceBuilder.sort(sortBuilder);
            sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
            request.source(sourceBuilder);
            SearchResponse searchResponse = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (SearchHit documentFields : searchResponse.getHits().getHits()) {
                HighlightField title = documentFields.getHighlightFields().get(Field);
                Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
                if(null != title) {
                    StringBuilder highField = new StringBuilder();
                    Text[] fragments = title.fragments();
                    for (Text fragment : fragments) {
                        highField.append(fragment);
                    }
                    sourceAsMap.put("title",highField.toString());
                }
                list.add(sourceAsMap);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        for (Map<String, Object> ele : list) {
            long timeStamp = Long.parseLong(ele.get("createTime") + "");
            Date date = new Date(timeStamp);
            String format = sdf.format(date);
            ele.put("createTime",format);
            if(null != ele.get("newsTime")) {
                long updateStamp = Long.parseLong(ele.get("newsTime") + "");
                Date dateUpdate = new Date(updateStamp);
                String format1 = sdf.format(dateUpdate);
                ele.put("newsTime",format1);
            }
        }
        return list;
    }
}
